<?php

namespace App\Http\Controllers;

use Illuminate\Http\Request;
use App\Models\SArticleInfo as ArticleModel;
use App\Models\SShareLog as ShartModel;
use App\Models\SCloudLessonInfo as CloudLessonModel;
use App\Models\SOrderInfo as OrderModel;


class ShareController extends BaseController
{
        //分享回调
    public function shareLessonCallBack()
    {
        $info_type  = request("infoType", 1);
        $info_id    = request("infoId");
        $shart_type = request('shartType', 10);

        //根据权限，获取用户id
        $user_id = 3;

        if( $infoType == 0 ) {
        	//云课堂
        	$cloudLesson = CloudLessonModel::find('id', $info_id);
        	$cloudLesson->share_num++;
        	$cloudLesson->save();

        } else if( $infoType == 1 ) {
        	//好文
        	
        }

        $ret = ShartModel::insert([
        	'info_type'  => $info_type,
        	'info_id'    => $info_id,
        	'shart_type' => $shart_type,
        	'user_id'    => $user_id,
        	'created_at' => now()
        ]);

        if($info_type == 1 && $ret) {


        	$oid = $this->checkUserHasLesson($info_type, $info_id, $user_id);

        	if($oid) {
        		return;
        	}

        	$userShareNum = $this->getUserShareLessonNum($info_type, $info_id, $user_id);

			if ( $userShareNum >= $cloudLesson->require_share_num ) {

				$this->addUserLesson($info_type, $info_id, $user_id);
			}
        }
    }

    //检测用户是否已经购买该书
    protected function checkUserHasLesson($info_type, $info_id, $user_id)
    {
    	return OrderModel::where([
		    		'info_id' => $info_id,
		    		'user_id' => $user_id,
		    		'info_type' => $info_type,
		    	])
		    	->value("id");
    }

    //获取分享次数
    protected function getUserShareLessonNum($info_type, $info_id, $user_id)
    {
    	return ShartModel::where([
				        		['user_id', $user_id],
				        		['info_id', $info_id],
				        		['info_type', $info_type],
				        	])
				        	->count();
    }

    //加入用户订单
    protected function addUserLesson($info_type, $info_id, $user_id)
    {
    	return OrderModel::insert([
				'user_id'   => $user_id,
				'info_id'   => $info_id,
				'info_type' => $info_type,
			]);
    }
}
